import requests
import json
import re
import pandas as pd

API_KEY = "yzL8hbRpdo9CV7r9HTJX8xoz"
SECRET_KEY = "AQgNomX5uvA2v0IobGn4Irw4GQv1Pm2e"
CO2_DATA_CSV_PATH = 'co2_data.csv'

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

def get_weather_info(city):
    key = "c04a6abed6fcd59532a2e9176dc56a9e"
    url = "https://restapi.amap.com/v3/weather/weatherInfo"
    params = {
        "key": key,
        "city": city,
        "extensions": "base",
        "output": "json"
    }
    response = requests.get(url, params=params)
    data = response.json()

    if 'lives' in data and len(data['lives']) > 0:
        weather = data['lives'][0].get('weather')
        temperature = data['lives'][0].get('temperature')
        return weather, temperature
    else:
        raise ValueError("无法获取天气信息，请检查城市名称或者API响应。")

def get_co2_data():
    df = pd.read_csv(CO2_DATA_CSV_PATH)
    return df['predicted_value'].tolist()

def get_wenxin_response(question, weather, co2):
    url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token={get_access_token()}"

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": f"{question} 今天天气是{weather}，预计碳排放量是{co2}吨，给出今天的出行建议。"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    response_text = response.text
    response_text = re.sub(r'[^\u4e00-\u9fa5，。！？、；：“”‘’（）【】《》]+', '', response_text)
    return response_text


